﻿// SMIL is a community project available under the Microsoft Public License (Ms-PL)
// Code is provided as is and with no warrenty – Use at your own risk
// View the project and the latest code at http://smil.codeplex.com/


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Maps.MapControl;

using DeepEarth.BingMapsToolkit.Client.MapGeometry;
using DeepEarth.BingMapsToolkit.Client.Common;
using SMIL.DrawingTools;
using SMIL.ApplicationVariables;

using System.Windows.Controls.Primitives;

using System.Windows.Browser;

namespace SMIL.Client.CoordinateXAP
{
    public partial class MainPage : UserControl
    {
        
        int isViewing = 0;

        string idInBrowserForTextField = string.Empty;
        //HtmlDocument doc;

        //Dictionary<string, DeepEarth.BingMapsToolkit.Client.Common.Entities.StyleSpecification> styles;
        CanvasState canvasState;
        PanelState panelState;

        EnhancedMapLayer renderLayer;
        

        public MainPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainPage_Loaded);      
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            string bingKey = GetParamFromSharePoint("getInputParam", new string[]{"input", "lBingKey"});
            map.CredentialsProvider = new ApplicationIdCredentialsProvider(bingKey);
            AddToApplicationResources(ApplicationVariables.ApplicationVariables.BingKey.ToString(), bingKey);
            
            string href = (string)HtmlPage.Window.Invoke("getUrl");
            SetIsViewing(href);
            SetApplicationVariables(isViewing);
            SetGeoRssPath();
  
            sPanel.MouseEnter += new MouseEventHandler(sPanel_MouseEnter);
            sPanel.MouseLeave += new MouseEventHandler(sPanel_MouseLeave);
            this.KeyUp += new KeyEventHandler(MainPage_KeyUp);

            renderLayer = new EnhancedMapLayer(map);
            drawingTool.ScratchLayer = renderLayer;
            
            
            DrawStoredGeometries();
            
            panelState = PanelState.Unlocked;

            //if (isViewing == 0)
            //{
            //    SMIL.FileUploadClient.FileUpload fileUpload = new FileUploadClient.FileUpload { ParentMap = map };
            //    fileUpload.Uploadlayer = renderLayer;
            //    fileUpload.LabelLayer = renderLayer;
            //}

            //layer.SPSiteURI = Application.Current.Resources[SMIL.ApplicationVariables.ApplicationVariables.SPSite.ToString()] as string;

            //layerControl.SiteURL = Application.Current.Resources[SMIL.ApplicationVariables.ApplicationVariables.SPSite.ToString()] as string; 
            //layerControl.Load(map, Application.Current.Resources[SMIL.ApplicationVariables.ApplicationVariables.SPSite.ToString()] as string); 

        }

        private void SetGeoRssPath()
        {
            SMIL.SPCommunication.Proxy.ServiceAddress =
                string.Concat(
                Application.Current.Resources[SMIL.ApplicationVariables.ApplicationVariables.SPSite.ToString()] as string,
                "/_layouts/SPGeoRss.asmx");
        }

        private static void SetApplicationVariables(int isViewing)
        {
            if (!Application.Current.IsRunningOutOfBrowser)
            {
                System.Windows.Browser.HtmlDocument doc = System.Windows.Browser.HtmlPage.Document;

                string site = GetParamFromSharePoint("getInputParam", new string[] { "input", "lSMILSite" });
                AddToApplicationResources(ApplicationVariables.ApplicationVariables.SPSite.ToString(), site);

                string lSCAStatus = GetParamFromSharePoint("getInputParam", new string[] { "input", "lSCAStatus" });
                AddToApplicationResources(ApplicationVariables.ApplicationVariables.Status.ToString(), lSCAStatus);

                AddToApplicationResources(ApplicationVariables.ApplicationVariables.IsInDataField.ToString(), "true");

                if (isViewing == 0)
                {
                    string documentLibrary = GetParamFromSharePoint("getInputParam", new string[] { "input", "lDocumentLibrary" });
                    AddToApplicationResources(ApplicationVariables.ApplicationVariables.DocumentLibrary.ToString(), documentLibrary);

                    string coordinateFieldNameInForeignColumn = GetParamFromSharePoint("getInputParam", new string[] { "input", "lCoordinateFieldNameInForeignColumn" });
                    AddToApplicationResources(ApplicationVariables.ApplicationVariables.CoordinateFieldNameInForeignColumn.ToString(), coordinateFieldNameInForeignColumn);

                    string spItemID = GetParamFromSharePoint("getInputParam", new string[] { "input", "lItemID" });
                    AddToApplicationResources(ApplicationVariables.ApplicationVariables.ItemID.ToString(), spItemID);

                    string listName = GetParamFromSharePoint("getInputParam", new string[] { "input", "lThisList" });
                    AddToApplicationResources(ApplicationVariables.ApplicationVariables.List.ToString(), listName);
                }
            }
        }

        static void AddToApplicationResources(string key, string value)
        {
            if (string.IsNullOrEmpty(value))
                return;

            if (!Application.Current.Resources.Contains(key))
                Application.Current.Resources.Add(key, value);
        }

        static string GetParamFromSharePoint(string tag, string[] parameters)
        {
            return HtmlPage.Window.Invoke("getInputParam", parameters) as string;
        }

        void MainPage_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                SetCursor();
            }
        }

        private void SetCursor()
        {
            Cursor = Cursors.Arrow;
            canvasState = CanvasState.None;
        }

        #region Mouse
        void sPanel_MouseLeave(object sender, MouseEventArgs e)
        {
            if (isViewing == 0 && panelState == PanelState.Unlocked)
                VisualStateManager.GoToState(this, "My2ndMouseState", true);
        }

        void sPanel_MouseEnter(object sender, MouseEventArgs e)
        {
            if (isViewing == 0)
                VisualStateManager.GoToState(this, "MyMouseEnter", true);
        }

        #endregion

        private void DrawStoredGeometries()
        {

            if (!Application.Current.IsRunningOutOfBrowser)
            {
                string styledGeometries = string.Empty;

                SMIL.Geometry.StyledGeometry styledGeometry = new Geometry.StyledGeometry(map);

                if (isViewing == 1)
                {
                    string id = GetIDFromSP("input", "lCoordinate");
                    if (!string.IsNullOrEmpty(id))
                    {
                        styledGeometries = (string)HtmlPage.Window.Invoke("getStyledGeometries", new string[] { id });
                        RenderGeometries(styledGeometries, styledGeometry, Geometry.RenderState.ViewingNoInfoBox);
                    }
                }
                else
                {
                    string id = GetIDFromSP("span", "lCoordinate");

                    if (!string.IsNullOrEmpty(id))
                    {
                        id = id.Replace("lCoordinate", "TextField");
                        styledGeometries = (string)HtmlPage.Window.Invoke("getStyledGeometries", new string[] { id });
                        RenderGeometries(styledGeometries, styledGeometry, Geometry.RenderState.Editing);
                    }
                }
            }
        }

        void RenderGeometries(string geometries, SMIL.Geometry.StyledGeometry styledGeometry, Geometry.RenderState renderState)
        {

            if (string.IsNullOrEmpty(geometries))
                return;

            if (!map.Children.Contains(renderLayer))
                map.Children.Add(renderLayer);

            LocationRect locationRect = styledGeometry.RenderGeometries(map, renderLayer, geometries, renderState);
            map.SetView(locationRect);
            map.ZoomLevel--;
        }

        string GetIDFromSP(string elementName, string elementID)
        {
            return (string)HtmlPage.Window.Invoke("getTagFromTitle", new string[] { elementName, elementID });
        }

        private void SetIsViewing(string href)
        {
            if (href.Contains("DispForm.aspx")) // Display view
            {
                isViewing++;
            }
        }

        private static void AdjustForCultureOnSetStartCoordinates(string coordinates, out double lat, out double lon, out double zoom)
        {
            System.Globalization.CultureInfo cultureInfo = 
                new System.Globalization.CultureInfo(System.Globalization.CultureInfo.CurrentCulture.Name); 
            cultureInfo.NumberFormat.NumberDecimalSeparator = ".";
            string[] pieces = coordinates.Split(new char[] { ' ', '=' }, StringSplitOptions.RemoveEmptyEntries);
            
            lat = double.Parse(pieces[1].Replace(',', '.'), cultureInfo.NumberFormat);
            lon = double.Parse(pieces[3].Replace(',', '.'), cultureInfo.NumberFormat);
            zoom = double.Parse(pieces[5].Replace(',', '.'), cultureInfo.NumberFormat);
        }
        
        #region Pin_MouseEnterLeave
        void pin_MouseLeave(object sender, MouseEventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        void pin_MouseEnter(object sender, MouseEventArgs e)
        {
            if (isViewing == 0)
                Cursor = Cursors.Hand;
        }
        #endregion

        private void bFullScreen_Click(object sender, RoutedEventArgs e)
        {
            App.Current.Host.Content.IsFullScreen = !App.Current.Host.Content.IsFullScreen;
        }

        private void DeleteSelectedGeom(SelectGeometry selectGeometry)
        {
            selectGeometry.Dispose();
            SetCursor();
        
        }

        private void tbDelete_Checked(object sender, RoutedEventArgs e)
        {
            canvasState = CanvasState.Deleting;
            Cursor = Cursors.Eraser;
        }

        
        #region nested states
        enum CanvasState
        {
            None = 0,
            Drawing = 1,
            Deleting = 2
        }

        enum PanelState
        {
            None = 0,
            Locked = 1,
            Unlocked = 2
        }
        #endregion

        private void Image_GrayPinLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (panelState == PanelState.Locked)
            {
                panelState = PanelState.Unlocked;
                imageAngle.Angle = 90;
            }
            else
            {
                panelState = PanelState.Locked;
                imageAngle.Angle = 0;
            }            
        }

        private void bSearch_Click(object sender, RoutedEventArgs e)
        {
            searchPanel.Open();
        }


        private void bMini_Click(object sender, RoutedEventArgs e)
        {
            miniMapPanel.Open();
        }
    }
}
